<?php

class EmpresaController extends AweController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    public $defaultAction = 'admin';

    public function filters() {
        return array(
            array('CrugeAccessControlFilter'),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        Yii::import("xupload.models.XUploadForm");
        $archivos = new XUploadForm;

        $this->render('view', array(
            'model' => $this->loadModel($id),
            'archivos' => $archivos,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Empresa;
        $model->Emp_FecRegistro = Util::FechaActual();
        //ajax Validate
        if (isset($_POST['ajax']) && $_POST['ajax'] === '#empresa-form') {
            $model->attributes = $_POST['Empresa'];
            $result['success'] = $model->validate();
            if (!$result['success']) {
                $result['errors'] = $model->errors;
                echo json_encode($result);
                Yii::app()->end();
            }
        }
        if (isset($_POST['Empresa'])) {
            $model->attributes = $_POST['Empresa'];
            $result['success'] = $model->save();
            if ($result['success']) {
                $result['data'] = array('entidad_id' => $model->Emp_Codigo, 'entidad_tipo' => 'EMPRESA');
                echo CJSON::encode($result);
            }
        } else {
            $this->render('form_wizard', array(
                'model' => $model,
            ));
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        $model->Emp_FecModificacion = Util::FechaActual();
        if (!empty($model->Emp_Seg_Codigo)) {
            $model->segmento = $model->empSegCodigo->SubSeg_Seg_Codigo;
        }
        //ajax Validate
        if (isset($_POST['ajax']) && $_POST['ajax'] === '#empresa-form') {
            $model->attributes = $_POST['Empresa'];
            $result['success'] = $model->validate();
            if (!$result['success']) {
                $result['errors'] = $model->errors;
                echo json_encode($result);
                Yii::app()->end();
            }
        }
        if (isset($_POST['Empresa'])) {
            $model->attributes = $_POST['Empresa'];
            $result['success'] = $model->save();
            if ($result['success']) {
                $result['data'] = array('entidad_id' => $model->Emp_Codigo, 'entidad_tipo' => 'EMPRESA');
                // Crear registro de actividad
                echo CJSON::encode($result);
            }
        } else {
            $this->render('form_wizard', array(
                'model' => $model,
            ));
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
//    public function actionAdmin() {
//        $model = new Empresa('search');
//        $model->unsetAttributes(); // clear any default values
//        if (isset($_GET['Empresa'])) {
//            $model->attributes = $_GET['Empresa'];
//        }
//        if ($model->count() > 0) {
//            $this->render('admin', array('model' => $model));
//        } else {
//            $this->render('empty');
//        }
//    }
    //cr
    public function actionAdmin() {
        $model = new Empresa('search');
        $model->unsetAttributes(); // clear any default values

        if (isset($_GET['search'])) {
            $model->attributes = $this->assignParams($_GET['search']);
        }

        if ($model->count() > 0) {
            $this->render('admin', array('model' => $model));
        } else {
            $this->render('empty');
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = Empresa::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'empresa-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public static function actionObtenerSubsegmento() {
        if (isset($_POST['Empresa']['segmento'])) {
            $data = Subsegmento::model()->findAll(array(
                "condition" => "SubSeg_Seg_Codigo =:segmento ",
                "order" => "SubSeg_Nombre",
                "params" => array(':segmento' => $_POST['Empresa']['segmento'],)
            ));
            if ($data) {
                $data = CHtml::listData($data, 'SubSeg_Codigo', 'SubSeg_Nombre');
                echo CHtml::tag('option', array('value' => ''), '- Seleccione -', true);
                foreach ($data as $value => $name) {
                    echo CHtml::tag(
                            'option', array('value' => $value), CHtml::encode($name), true);
                }
            } else {
                echo CHtml::tag('option', array('value' => ''), '- No existen opciones -', true);
            }
        } else {
            echo CHtml::tag('option', array('value' => ''), '- Seleccione un segmento -', true);
        }
    }

    public function actionAjaxlistCuentas($search_value = null) {
        if (Yii::app()->request->isAjaxRequest) {
            echo CJSON::encode(Empresa::model()->getListSelect2($search_value));
        }
    }

    /*
      @author Cristian Araque<caraque@tradesystem.com.ec>
     *exportar los campos de la tabla de excel
     */
    public function actionExportExcelEmpresas() {
        $modelEmpresas = array();
//        var_dump($_POST);die();
        if ($_POST['Empresa'] == 'todos') {
            //datos del filtro
            $filtros = $_POST['Busqueda'];
            
            $modelEmpresas = Empresa::model()->getEmpresaSearch(null,$filtros);
        } else {
            $empresas = $_POST['Empresa'];
            
            
            $modelEmpresas = Empresa::model()->getEmpresaSearch($empresas);
        }
        $objExcel = new PHPExcel();
        //los titulos del excel
        $objExcel->setActiveSheetIndex(0)
                //Titulo de las columnas
                ->setCellValue('A1', 'Razón Social')
                ->setCellValue('B1', 'RUC')
                ->setCellValue('C1', 'Grupo')
                ->setCellValue('D1', 'Categoría')
                ->setCellValue('E1', 'Clase')
                ->setCellValue('F1', 'Grupo Económico')
                ->setCellValue('G1', 'Sub-segmento')
                ->setCellValue('H1', 'Estado')
                ->setCellValue('I1', 'Eje Codigo')
                ->setCellValue('J1', 'Sadeg Codigo')
                ->setCellValue('K1', 'Observación')
                ->setCellValue('L1', 'Ciudad');
        $id = 2;
        foreach ($modelEmpresas as $empresa) {
            $objExcel->setActiveSheetIndex(0)
                    //campos que viene de la consulta
                    ->setCellValue('A' . $id, $empresa['RazonSocial'])
                    ->setCellValue('B' . $id, $empresa['RUC'])  //Titulo de las columnas
                    ->setCellValue('C' . $id, $empresa['Grupo'])
                    ->setCellValue('D' . $id, $empresa['Categoria'])
                    ->setCellValue('E' . $id, $empresa['Clase'])
                    ->setCellValue('F' . $id, $empresa['GrupoEconomico'])
                    ->setCellValue('G' . $id, $empresa['Segmento'])
                    ->setCellValue('H' . $id, $empresa['Estado'])
                    ->setCellValue('I' . $id, $empresa['Ejecutivo'])
                    ->setCellValue('J' . $id, $empresa['Sadeg'])
                    ->setCellValue('K' . $id, $empresa['Observacion'])
                    ->setCellValue('L' . $id, $empresa['Ciudad']);
            $id++;
        }
        for ($i = 'A'; $i <= 'L'; $i++) {
            $objExcel->setActiveSheetIndex(0)->getColumnDimension($i)->setAutoSize(TRUE);
        }
        $objExcel->getActiveSheet()->setTitle('Empresas');

        //// Se activa la hoja para que sea la que se muestre cuando el archivo se abre
        $objExcel->setActiveSheetIndex(0);

        //// Inmovilizar paneles
        $objExcel->getActiveSheet(0)->freezePane('A4');
        $objExcel->getActiveSheet(0)->freezePaneByColumnAndRow(1, 2);
        // Se manda el archivo al navegador web, con el nombre que se indica, en formato 2007
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="ReporteEmpresas.xlsx"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    /*
      @author Cristian Araque<caraque@tradesystem.com.ec>
     *
     */
    public function assignParams($params) {
        $result = array();
//        var_dump($params);
        if ($params['filters'][0] == 'all') {
            foreach (Empresa::model()->searchParams() as $param) {
                $result[$param] = $params['value'];
            }
        } else {
            foreach ($params['filters'] as $param) {
                $result[$param] = $params['value'];
            }
        }
        return $result;
    }
}
